package com.baiyang.server.service.base.impl;


import com.baiyang.server.model.base.Goods;
import com.baiyang.server.model.base.UserIntegral;
import com.baiyang.server.model.system.User;
import com.baiyang.server.service.base.GoodsService;
import com.baiyang.server.service.base.UserIntegralService;
import com.baiyang.server.service.impl.BaseServiceImpl;
import com.baiyang.server.tools.DataTool;
import com.baiyang.server.tools.Letter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baiyang.server.dao.base.ExchangeDao;
import com.baiyang.server.model.base.Exchange;
import com.baiyang.server.service.base.ExchangeService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author XVX
 * BY: @Primary 注解帮助生命@Autowired优先注入的实列
 */
@Service	
public class ExchangeServiceImpl extends BaseServiceImpl<ExchangeDao, Exchange> implements ExchangeService{
    @Autowired
    private ExchangeDao exchangeDao;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserIntegralService userIntegralService;
    @Transactional
    @Override
    public void exchange(Exchange exchange, Letter<String> letter) {
        String goodId = exchange.getGoodId();
        Goods goods = new Goods();
        goods.setId(goodId);
        goods = goodsService.selectOne(goods);
        if(goods == null){
            letter.setResult("FAIL");
            letter.setDetail("数据异常");
            return ;
        }
        String userId = exchange.getUserId();
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral = userIntegralService.selectOne(userIntegral);
        if(userIntegral == null){
            letter.setResult("FAIL");
            letter.setDetail("数据异常");
            return ;
        }
        if(goods.getRequiredNum() > userIntegral.getIntegralNum()){
            letter.setResult("FAIL");
            letter.setDetail("积分不足无法兑换");
            return ;
        }
        if(goods.getLaveNum() == 0){
            letter.setResult("FAIL");
            letter.setDetail("商品数量不足不能进行兑换！");
            return ;
        }
        // 更改用户积分
        userIntegral.setIntegralNum(userIntegral.getIntegralNum() - goods.getRequiredNum());
        userIntegralService.updateById(userIntegral);
        // 更改商品剩余数量
        goods.setLaveNum(goods.getLaveNum() - 1);
        goodsService.updateById(goods);
        // 插入兑换信息
        exchange.setId(DataTool.createUUID());
        exchange.setSpendNum(goods.getRequiredNum());
        exchangeDao.insert(exchange);
        letter.setResult("SUCCESS");
        letter.setDetail("兑换成功");
    }
}
